package com.compass.mobile.ui.fragment

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.leanback.widget.ArrayObjectAdapter
import androidx.leanback.widget.BaseGridView
import androidx.leanback.widget.FocusHighlight
import androidx.leanback.widget.FocusHighlightHelper
import com.compass.mobile.R
import com.compass.mobile.callback.OnItemClickListener
import com.compass.mobile.databinding.FragmentCaseItemBinding
import com.compass.mobile.framework.base.BaseVBFragment
import com.compass.mobile.framework.constant.PRESCRIPTION
import com.compass.mobile.framework.constant.YD_USER_ID
import com.compass.mobile.framework.ext.gone
import com.compass.mobile.framework.ext.onClick
import com.compass.mobile.framework.ext.visible
import com.compass.mobile.framework.utils.FocusViewUtils
import com.compass.mobile.framework.utils.dpToPx
import com.compass.mobile.models.PrescriptionRecord
import com.compass.mobile.presenters.PrescriptionPresenter
import com.compass.mobile.ui.dialog.CodeDialog
import com.compass.mobile.ui.dialog.CommonMessageDialog
import com.compass.mobile.ui.viewModel.PersonalCenterViewModel
import com.compass.mobile.widget.MyBridgeAdapter
import getStringFromResource

/**
 * Description： 申请需方
 * Date:2024/7/4 9:17
 */
class FollowingPrescriptionFragment : BaseVBFragment<FragmentCaseItemBinding>() {
    private val personalCenterViewModel: PersonalCenterViewModel by viewModels()

    private var orders: MutableList<PrescriptionRecord> = mutableListOf()
    private lateinit var arrayObjectAdapter: ArrayObjectAdapter
    private var mPage = 1
    private var isHaveNext = true
    private var type: String = ""
    override fun initView(view: View, savedInstanceState: Bundle?) {
        specialColumn()
        FocusViewUtils.scaleView(mBinding?.tvPrevious, 1)
        FocusViewUtils.scaleView(mBinding?.tvNextPage, 1)

    }


    override fun initData() {
        personalCenterViewModel.prescriptionRecords(UserInfoManager.getPatientInfo()?.id, type,mPage )
        personalCenterViewModel.prescriptionsLiveData.observe(this) {
            dismissLoading()
            if (mPage == 1) {
                if (it.isNullOrEmpty()) {
                    isHaveNext(0)
                    mBinding?.emptyView?.visible()
                    mBinding?.llBelow?.gone()
                } else {
                    isHaveNext(it.size)
                    mBinding?.emptyView?.gone()
                    orders = it
                    arrayObjectAdapter.clear()
                    arrayObjectAdapter.addAll(0, orders)
                }
            } else {
                if (it.isNullOrEmpty()) {
                    isHaveNext(0)
                    mPage-- //恢复上一次的page
                    showToast("没有下一页了")
                } else {
                    isHaveNext(it.size)
                    orders = it
                    arrayObjectAdapter.clear()
                    arrayObjectAdapter.addAll(0, orders)
                }
            }
        }
        personalCenterViewModel.continuePrescriptionLiveData.observe(this) {
            dismissLoading()
            it?.let {
                showToast("申请成功，已向医生发起通知")

            }
        }
    }

    private fun isHaveNext(number: Int) {
        if (number < 10) {
            isHaveNext = false
        } else {
            mBinding?.llBelow?.visible()
            isHaveNext = true
        }
    }


    override fun intListener() {
        mBinding?.tvPrevious?.onClick {
            if (mPage > 1) {
                mPage--
                personalCenterViewModel.prescriptionRecords(
                    UserInfoManager.getPatientInfo()?.id,
                    type,
                    mPage
                )
            } else {
                showToast("没有上一页了")
            }
        }

        mBinding?.tvNextPage?.onClick {
            if (isHaveNext) {
                mPage++
                personalCenterViewModel.prescriptionRecords(
                    UserInfoManager.getPatientInfo()?.id,
                    type,
                    mPage
                )
            } else {
                showToast("没有下一页了")
            }
        }
    }


    private val onItemClickListener: OnItemClickListener = object : OnItemClickListener {
        override fun onItemClick(position: Int, view: View) {
            val item = orders[position]


            when (item.status) {
                "4" -> {
                    //续方
                    if (item.isTransfer=="0"){
                        CommonMessageDialog.Builder(requireActivity())
                            .setTitle("温馨提示")
                            .setMessage("确认要向医生发出续方申请吗??")
                            .setConfirm(getStringFromResource(R.string.default_confirm))
                            .setCancel(getString(R.string.default_cancel))
                            .setonCancelListener {
                                it?.dismiss()
                            }
                            .setonConfirmListener {

                                it?.dismiss()
                                personalCenterViewModel.continuePrescription(item.id)
                                showLoading()
                            }.create().show()
                    }else{
                        showToast("迁移处方，不支持续方")
                    }
                }

                "1" -> {
                    //支付
                    val oderCodeDialog =
                        CodeDialog.Builder(
                            requireActivity(),
                            PRESCRIPTION + UserInfoManager.getString(YD_USER_ID)
                        )
                    oderCodeDialog.show()
                }

                else -> {

                }
            }


        }
    }


    @SuppressLint("RestrictedApi")
    fun specialColumn() {

        mBinding?.caseItem?.horizontalSpacing = dpToPx(10)
        mBinding?.caseItem?.verticalSpacing = dpToPx(10)

        arrayObjectAdapter = ArrayObjectAdapter(PrescriptionPresenter())
        val itemBridgeAdapter = MyBridgeAdapter(
            requireContext(),
            arrayObjectAdapter, onItemClickListener
        )

        mBinding?.caseItem?.setAdapter(itemBridgeAdapter)
        mBinding?.caseItem?.setFocusScrollStrategy(BaseGridView.FOCUS_SCROLL_ITEM)
        arrayObjectAdapter.addAll(0, orders)
        FocusHighlightHelper.setupBrowseItemFocusHighlight(
            itemBridgeAdapter,
            FocusHighlight.ZOOM_FACTOR_NONE, false
        )
    }
}